# -*- coding: utf-8 -*-s
from urllib2 import URLError
import time

from pyquery import PyQuery

from export.distributors.b2b import B2b
from export.models import Currency, ProductsLink, B2b_Price, B2b as Btob, B2b_Category
from settings import db


class Stack(B2b):
    host = 'https://web.stek.com.ua/'
    mainUrl = 'https://web.stek.com.ua/start.asp'
    searchUrl = 'List_TMC.asp'
    b2b = Btob.objects.get_or_create(b2b_name='stek')[0]

    def __init__(self, content=None):
        B2b.__init__(self)
        if content:
            self.jQuery = PyQuery(content)
        self.setCurrency(Currency.objects.all()[0].currency)

    def setCurrency(self, currency):
        if currency:
            self.currency = currency
            # else:
            #     jQuery = PyQuery(self.browser.open(self.host + 'logo.asp').get_data())
            #     currency = jQuery('.PuncktTD2')
            #     self.currency = float(currency[1].text[currency[1].text.find('$:') + 2:])

    def search(self, query):
        product_ = ProductsLink.objects.filter(sku=query)
        if product_:
            product = B2b_Price.objects.filter(product=product_)
            if product:
                avail = False
                category = False
                price = False
                for pr in product:
                    if pr.b2b_id == self.b2b.id:
                        if pr.price_rule:
                            price = pr.price_rule.encode('utf-8').replace(' ', '').split(';')
                            category = pr.b2b_category.category.encode('utf-8')
                            if pr.avail:
                                avail = pr.avail
                        else:
                            return False, False, False
                    else:
                        if pr.avail:
                            avail = pr.avail
                return category, avail, price
        return False, False, False

    def updatePrice(self):
        # params = {'operation': 1, 'pricenum': 7}
        # content = open(
        #     self.browser.open(self.host + 'List_Prices.asp', urllib.urlencode(params))[0]).read()
        # self.setPrice(content)
        pass

    def setPrice(self):
        if self.jQuery:
            B2b_Price.objects.filter(b2b_id=self.b2b.id).update(avail=False)
            for cat in B2b_Category.objects.all():
                cat.delete = True
                cat.save()
            products_ = self.jQuery('partnumber')
            for product_ in products_:
                productSku = product_.text
                productId = self.getProductIdBySku(productSku)
                if productId:
                    product = ProductsLink.objects.get_or_create(entity_id=productId)[0]
                    product.sku = productSku
                    product.name = self.getProductNameById(productId)
                    product.save()
                    productPrice = B2b_Price.objects.get_or_create(product=product, b2b=self.b2b)[0]
                    productPrice.last_update = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
                    productPrice.category = self.getCategoriesByProductId(product.entity_id)
                    attrib = self.jQuery(product_).parent()[0].attrib
                    productPrice.avail = True if attrib['ostatok_lviv'] != "0" or attrib['ostatok_kyyiv'] != "0" \
                                                     or attrib['ostatok_odesa'] != "0" else False
                    productPrice.price_rule = '%s;%s;%s;%s' % (
                        attrib['cena_dyler'], attrib['cena_gurt'], attrib['cena_dribnyj_gurt'], attrib['cena_rozdrib'])
                    category = self.getCategoryByProductInPrice(product_)
                    category = self.getB2bCategoryWithStatus(category)
                    productPrice.b2b_category = category
                    productPrice.b2b_name = self.jQuery(self.jQuery(product_).parent()[0]).children()[0].text
                    productPrice.change_avail = None
                    productPrice.change_price = None
                    productPrice.save()

    def getProductNameById(self, id):
        attrId = self.getAttrByCode('name')
        return db.sqlQuery('''SELECT value FROM firstcatalog_product_entity_varchar
                            where attribute_id=%s and entity_id=%s;''' % (attrId, id))[0][0]

    def getAttrByCode(self, code):
        return db.sqlQuery('''SELECT * FROM firsteav_attribute where attribute_code='%s'
                            and entity_type_id=4;''' % code)[0][0]

    def getB2bCategoryWithStatus(self, category):
        try:
            category = B2b_Category.objects.get(b2b_id=self.b2b, category=category)
            category.delete = False
        except B2b_Category.DoesNotExist:
            category = B2b_Category.objects.create(b2b_id=self.b2b, category=category, new=True, delete=False)
        finally:
            category.save()
        return category

    def getCategoryByProductInPrice(self, product):
        status = True
        parent = self.jQuery(product).parent()[0]
        categories = ''
        while status:
            status = False
            parent = self.jQuery(parent).parent()[0]
            if parent.attrib.has_key('isgroup'):
                status = True
                if parent.attrib['isgroup'] == '1':
                    children = self.jQuery(parent).children()
                    for child in children:
                        if child.tag == 'name':
                            if categories:
                                categories = '%s|%s' % (child.text.encode('utf-8').replace(' ', ''), categories)
                            else:
                                categories = child.text.encode('utf-8').replace(' ', '')
                            break
        return categories


    def getProductIdBySku(self, sku):
        var = db.sqlQuery('''SELECT * FROM firstcatalog_product_entity where sku="%s";''' % sku)
        if var:
            return var[0][0]
        else:
            return False

    def getCategoriesByProductId(self, productId):
        categories_ = db.sqlQuery(
            '''SELECT * FROM firstcatalog_category_product where product_id=%s;''' % productId)
        categories = ''
        if categories_:
            for category_ in categories_:
                categories += ',%s' % category_[0]
            categories = categories[1:]
        return categories


    # def search(self. query):
    #     if self.jQuery:
    #         products = self.jQuery('partnumber')


    def isLogin(self, page):
        return self.mainUrl == page

    def login(self):
        try:
            self.browser.open(self.host)
            if self.isLogin(self.browser.geturl()):
                return True
            self.browser.select_form(nr=0)
            self.browser['UserLogin'] = '63063'
            self.browser['UserPassword'] = '95984'
            self.browser.submit()
            if self.isLogin(self.browser.geturl()):
                return True
            else:
                return False
        except Exception:
            time.sleep(60)
            self.login()

    def searchBySitePage(self, query, categoryName):
        self.login()
        if query:
            self.browser.open(self.host + self.searchUrl)
            self.browser.select_form(nr=0)
            self.browser['sstr'] = query
            self.browser.submit()
            jQuery = PyQuery(self.browser.response().get_data())
            link = jQuery('.wordbreak .nob a')
            if not link:
                return False, False, False
            params = jQuery(jQuery('.cT')[0]).nextAll()
            avail = True if jQuery(params[3]).text().find('+') != -1 or jQuery(params[4]).text().find(
                '+') != -1 or jQuery(params[5]).text().find('+') != -1 else False
            price = [jQuery(params[6]).text(), jQuery(params[7]).text(), jQuery(params[8]).text(),
                     jQuery(params[9]).text()]
            if len(link) == 1:
                self.browser.open(self.host + link[0].attrib['href'])
                jQueryCat = PyQuery(self.browser.response().get_data())
                categories = jQueryCat('.uT')
                categoriesName = []
                for category in categories:
                    categoriesName.append(jQueryCat(jQueryCat(category).children()[1]).text().encode('utf-8'))
                return categoriesName, avail, price
            else:
                return False, False, False

    def searchSKu(self, query):
        self.login()
        try:
            self.browser.open(self.host + self.searchUrl)
            self.browser.select_form(nr=0)
            self.browser['sstr'] = query
            self.browser.submit()
            jQuery = PyQuery(self.browser.response().get_data())
            links = jQuery('.wordbreak .nob a')
            if not links:
                return False
            for link in links:
                params = jQuery(link).parent().parent().parent().parent().parent().nextAll()
                if jQuery(params[1]).text().encode('utf-8').lower() == query.lower() or \
                                jQuery(params[0]).text().encode('utf-8').lower() == query.lower():
                    return link.text
        except Exception as ex:
            self.login()
            self.searchSKu(query).replace('\\', '').replace('\'', '')

    def getAllCategories(self):
        self.browser.open(self.host + 'List_TMC.asp')
        jQuery = PyQuery(self.browser.response().get_data())
        categories = {}
        categories_ = jQuery('.cT a')
        for category_ in categories_:
            categoryName = jQuery(category_).parent().next().children()[0].text
            categories[categoryName] = self.handlerHtmlCategory(categoryLink=category_.attrib['href'])
        return categories

    def getSubCategory(self, **kwargs):
        try:
            categoryLink = kwargs['categoryLink']
            self.browser.open(self.host + categoryLink)
            jQuery = PyQuery(self.browser.response().get_data())
            elements_ = jQuery('.cT a')
            categories = []
            if not elements_:
                return []
            for element in elements_:
                if not jQuery(element).children()[0].attrib.has_key('complete') and \
                                jQuery(element).children()[0].attrib['src'] == 'images/plusik.gif':
                    category = {}
                    categoryName = jQuery(element).parent().next().children()[0].text
                    category[categoryName] = self.handlerHtmlCategory(categoryLink=element.attrib['href'])
                    categories.append(category)
            return categories
        except URLError:
            self.login()
            self.getSubCategory(categoryLink=categoryLink)

    def handlerHtmlCatalog(self, **kwargs):
        self.login()
        self.browser.open(self.host + 'List_TMC.asp')
        jQuery = PyQuery(self.browser.response().get_data())
        categories = jQuery('.cT a')
        products = {}
        if kwargs.has_key('definiteCategoryName'):
            definiteCategoryName = kwargs['definiteCategoryName'].split('|')
            for category in categories:
                categoryName = jQuery(category).parent().next().children()[0].text
                if categoryName.replace(' ', '') == definiteCategoryName[0].replace(' ', ''):
                    products_ = self.handlerHtmlCategory(categoryLink=category.attrib['href'],
                                                         categoryName=categoryName,
                                                         definiteCategoryName=definiteCategoryName[1:])
                    products.update({kwargs['definiteCategoryName'].encode('utf-8'): products_})
            return self.proccessRule(products)
        for category in categories:
            categoryName = jQuery(category).parent().next().children()[0].text
            products.update(self.handlerHtmlCategory(categoryLink=category.attrib['href'], categoryName=categoryName))
        return products

    def handlerHtmlCategory(self, **kwargs):
        products = []
        try:
            categoryLink = kwargs['categoryLink']
            categoryName = kwargs['categoryName']
            definiteCategoryName = None
            if kwargs.has_key('definiteCategoryName'):
                definiteCategoryName = kwargs['definiteCategoryName']
            if kwargs.has_key('data'):
                self.browser.open(self.host + categoryLink, kwargs['data'])
            else:
                self.browser.open(self.host + categoryLink)
            jQuery = PyQuery(self.browser.response().get_data())
            elements_ = jQuery('.cT a')
            for element in elements_:
                if not jQuery(element).children()[0].attrib.has_key('complete') and element.attrib['href'] != '#' \
                    and jQuery(element).children()[0].attrib[
                            'src'] != 'images/plusik.gif' and not element.attrib.has_key('name') \
                    and not definiteCategoryName:
                    try:
                        product = self.handlerHtmlProduct(productLink=element.attrib['href'],
                                                          categoryName=categoryName)
                        params = jQuery(element).parent().nextAll()
                        product['code'] = params[1].text
                        if product['code']:
                            product['sku'] = jQuery(params[2]).text()
                            if self.checkProduct(product['sku']):
                                product['attrs'] = {}
                            if not product['sku']:
                                product['sku'] = 'bad_sku_stack_%s' % product['code']
                            product['price'] = [jQuery(params[7]).text(), jQuery(params[8]).text(),
                                                jQuery(params[9]).text(), jQuery(params[10]).text()]
                            products.append(product)
                    except Exception:
                        pass
                if not jQuery(element).children()[0].attrib.has_key('complete') and \
                                jQuery(element).children()[0].attrib['src'] == 'images/plusik.gif':
                    if definiteCategoryName:
                        categoryName = jQuery(element).parent().next().children()[0].text
                        if categoryName.replace(' ', '') == definiteCategoryName[0].replace(' ', ''):
                            products_ = self.handlerHtmlCategory(categoryLink=element.attrib['href'],
                                                                 categoryName=categoryName,
                                                                 definiteCategoryName=definiteCategoryName[1:])
                            if products_:
                                products += products_
                    else:
                        categoryName = jQuery(element).parent().next().children()[0].text
                        products_ = self.handlerHtmlCategory(categoryLink=element.attrib['href'],
                                                             categoryName=categoryName)
                        if products_:
                            products += products_
            return products
        except URLError:
            return 'стек помер'

    def handlerHtmlProduct(self, **kwargs):
        productLink = kwargs['productLink']
        categoryName = kwargs['categoryName']
        self.browser.open(self.host + productLink)
        jQuery = PyQuery(self.browser.response().get_data())
        product = {'name': jQuery('h3').text().replace("\"", ""), 'descr': jQuery('h5').text().replace("\"", ""),
                   'short_descr': jQuery('h3').text().replace("\"", "")}
        if not product['name']:
            product['name'] = product['descr']
            product['short_descr'] = product['descr']
        attr_ = jQuery('.cells_bcl')
        attr = {}
        i = 0
        while i < len(attr_):
            attr[attr_[i].text.encode('utf-8')] = attr_[i + 1].text.encode('utf-8')
            i += 2
        product['attrs'] = attr
        imagesLink = jQuery('img')
        images = []
        for image in imagesLink:
            images.append(image.attrib['src'])
        product['imagesLink'] = images
        return product